
import { uniLogin } from '@/utils/index';
import { SET_TOKEN, GET_TOKEN } from '@/utils/token';
import { userLoginApi, getUserInfoApi, getAddressListApi, userPointCountApi, userBonusCountApi } from '@/api/user';

const state = {
  token: GET_TOKEN(),
  userInfo: null, // 用户信息
  isVip: false,
  isLogin: false,
  isLoadedUser: false,
  addressList: [],
  userPointCount: 0,
  userBonusCount: 0,
}
const getters = {
  // 获取用户可用积分
  userInfo(state) {
    return state.userInfo
  },
  // 获取用户可用积分
  isVip(state) {
    return state.userInfo?.vip === 1
  },
  // 获取用户可用积分
  addressList(state) {
    return state.addressList
  },
}

const actions = {
  async userLogin({ commit, dispatch }, { code }) {
    try {
      uni.showLoading({ title: '登录中~' });
      const resCode = await uniLogin();
      // 登录请求
      const jsCode = resCode.code;
      const resToken = await userLoginApi({code, jsCode});
      // debugger
      commit('setToken', resToken)
      dispatch('getUserInfo')
      uni.hideLoading();
      // Toast('登录成功', 'success');
    } catch (error) {
      // Toast(error.message);
      console.error('error', error)
    } finally {
      uni.hideLoading();
    }
  },
  async getUserInfo({ commit, dispatch }, {silent = false} = {}){
    try {
      const res = await getUserInfoApi({}, { silent})
      commit('setUserInfo', res)
      commit('setIsLoadedUser')
    } finally {

    }

  },
  async getAddressList({ commit, dispatch }){
    const res = await getAddressListApi()
    commit('setAddressList', res)
    return res
  },

  async getUserPointCount({ commit, dispatch }){
    const res = await userPointCountApi()
    commit('setUserPointCount', res)
  },

  async getUserBonusCount({ commit, dispatch }){
    const res = await userBonusCountApi()
    commit('setUserBonusCount', res)
  },

  clearUserState({ commit, dispatch }) {
    commit('clearUserState')
  }
}
const mutations = {
  setToken(state, data) {
    SET_TOKEN(data)
    state.token = data
  },
  setUserInfo(state, data = {}) {
    state.userInfo = {...data }
    state.isVip = data.vip === 1
    state.isLogin = true
  },
  setIsLoadedUser(state) {
    state.isLoadedUser = true
  },
  setAddressList(state, data = []) {
    state.addressList = data
  },
  setUserPointCount(state, data= 0) {
    state.userPointCount = data
  },
  setUserBonusCount(state, data= 0) {
    state.userBonusCount = data
  },
  clearUserState(state) {
    state.token = ''
    state.userInfo = null
    state.isVip =  false
    state.isLogin =  false
    state.isLoadedUser =  true
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
}
